<?php

/**
 * Manages in-/output of data
 * @since  0.0.1
 *
 * Controllers are one of the three important parts of MVC. It reacts on input
 * from the user, reads and stores information from / in the Model and show
 * it to the client via View.
 *
 * They define how to read, evaluate, store and act on incoming data. An
 * instance can represent each file that's located in "/app/Controller"
 *
 *
 * @section CHANGELOG
 *
 * <table>
 * 	<tr>
 * 		<th>Version</th>
 * 		<th>Description</th>
 *  </tr>
 *  <tr><td>0.0.9</td><td>Class-variables useable within according PHP file</td></tr>
 * </table>
 *
 *
 * @section Examples
 *
 * @subsection Controller_Instance Define and use Controller
 * Firstly we want to make a Controller that sends something to the Client and
 * another one that get's it and delivers some values
 *
 * <pre>/app/Controller/index.php</pre>
 * @code
 * <?php
 *
 * echo "Foo is: " . $foo;
 *
 * ?>
 * @endcode
 *
 * <pre>Output "/":</pre>
 * @verbatim	Foo is: @endverbatim
 *
 * <pre>/app/Controller/test/test.php</pre>
 * @code
 * <?php
 *
 * $c = new Controller('index');	// get the controller /app/Controller/index.php
 * $c->foo = 123;					// put some data in it
 *
 * echo $c;						// dispatch
 * ?>
 * @endcode
 *
 * <pre>Output "/test":</pre>
 * @verbatim	Foo is: 123 @endverbatim
 *
 * <em class="note">Please use a View to correctly generate an output</em>
 *
 *
 * @see Model
 * @see View
 *
 *
 * New BSD License
 * \n
 * Copyright (c) 2010 Rpd-Team
 */
class Controller implements Pipeline
{
	private $_file = NULL, $_valid = false;
	protected $_map = array();

	function __set($item, $value)
	{
		$this->_map[$var] = $value;
	}

	function __get($item)
	{
		if (!isset($this->_map[$item]))
		{
			return NULL;
		}
		return $this->_map[$item];
	}

	function __invoke($in)
	{
		if (is_array($in))
		{
			$this->_map = array_replace(
		               		$this->_map,
		               		$in
			);
		}
		else if ($in instanceof Iterator)
		{
			$r = "";
			foreach ($in as $set)
			{
				$r .= (string) $this->__invoke($set);
			}

			return $r;
		}


		return $this;
	}


	function __construct($file = NULL)
	{
		if ($file === NULL)
		{
			$this->_file = DIR . FILE;
		}
		else
		{
			$this->_file = $file;
		}

		$append = Registry::get("controller/append");

		if (is_array($append))
		foreach ($append as $s)
		{
			if (   $s != ""
			    && file_exists("app/Controller/" . $this->_file . $s . ".php")
			    )
			{
				$this->_file .= $s;
			}
		}
	}

	function __toString()
	{
		global $site;

		if (file_exists("app/Controller/" . $this->_file . ".php"))
		{
			ob_start();
			extract($this->_map, EXTR_OVERWRITE & EXTR_REFS);
			include "app/Controller/" . $this->_file . ".php";
			return ob_get_clean();
		}
		else
		{
			$view = new View($this->_file);
			return (string) $view($this->_map);
		}
	}
}